package logic

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"luck/model/mysql"
	"luck/pkg"
	"strings"

	"luck/luckrpc/internal/svc"
	"luck/luckrpc/luckrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type OrderAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewOrderAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrderAddLogic {
	return &OrderAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *OrderAddLogic) OrderAdd(in *luckrpc.OrderAddRequest) (*luckrpc.OrderAddResponse, error) {
	// todo: add your logic here and delete this line
	//开启事务
	fxd := mysql.DB.Begin()

	var u mysql.User
	var p mysql.Product
	var err error
	err = fxd.Debug().Where("id=?", in.UserId).First(&u).Error
	if err != nil {
		fxd.Rollback()
		return nil, fmt.Errorf("用户不存在")
	}

	err = fxd.Debug().Where("id=?", in.ProductId).First(&p).Error
	if err != nil {
		fxd.Rollback()
		return nil, fmt.Errorf("饮品不存在,请重新选择饮品")
	}

	//判断库存
	if in.Quantity > p.Stock {
		fxd.Rollback()
		return nil, fmt.Errorf("库存不足")
	}

	//单件饮品总金额
	totalAmount := float64(in.Quantity) * p.Price

	//配送费
	var subtotal = 5.0

	//总金额
	total := totalAmount + subtotal
	//订单编号生成
	Sn := uuid.New().String()
	orderSn := strings.ReplaceAll(Sn, "-", "")
	orderSn = orderSn[:18]
	//订单表
	order := mysql.Order{
		UserId:  in.UserId,
		OrderSn: orderSn,
		Total:   totalAmount,
		Address: "",
		Status:  2,
		PayType: 2,
	}
	err = fxd.Debug().Create(&order).Error
	if err != nil {
		fxd.Rollback()
		return nil, fmt.Errorf("订单添加失败")
	}

	//订单商品表
	orderItem := mysql.OrderItem{
		OrderSn:      orderSn,
		ProductId:    uint(in.ProductId),
		ProductName:  p.Name,
		ProductPrice: p.Price,
		ProductImage: p.ImageUrl,
		Quantity:     int(in.Quantity),
		SubTotal:     total,
	}
	err = fxd.Debug().Create(&orderItem).Error
	if err != nil {
		fxd.Rollback()
		return nil, fmt.Errorf("订单商品表添加失败")
	}

	//库存扣减
	err = fxd.Debug().Model(mysql.Product{}).Where("id=?", in.ProductId).Update("stock", p.Stock-in.Quantity).Error
	if err != nil {
		fxd.Rollback()
		return nil, fmt.Errorf("库存扣减失败")
	}

	fxd.Commit()
	//订单支付
	amount := fmt.Sprintf("%.2f", total)
	url := pkg.Alipay(orderSn, amount)
	return &luckrpc.OrderAddResponse{
		OrderId: int64(order.ID),
		Total:   float32(total),
		OrderSn: orderSn,
		Url:     url,
	}, nil
}
